<style lang="scss">
    .scoped-coupon-details{
        .card{
            // margin: 0 auto;
            width: 500px;
        }
        .items{
            display: flex;
            flex-wrap: wrap;
            position: relative;
            >.item{
                display: inline-flex;
                flex-direction: column;
                align-items: center;
                justify-content: space-between;
                font-size: 10px;
                padding: 15px 30px;
                margin: 0;
                overflow: hidden;
                color: rgba(black, 0.6);
                img{
                    height: 15px;
                }
                >.item-name{
                    margin-top: 3px;
                }
            }
        }
        .reply{
            transition: .3s;
            color: rgba(black, 0.6);
            margin-right: 10px;
            &:hover{
                color:deepskyblue;
            }
        }

        .upload-list{
            $size:80px;
            .el-upload--picture-card{
                // 上传图片
                width: $size;
                height: $size;
                line-height: normal;
                display: inline-flex;
                justify-content: center;
                align-items: center;
                >i{
                    font-size: 16px;
                }
            }
            .el-upload-list--picture-card .el-upload-list__item{
                width: $size;
                height: $size;
            }
        }
    }
</style>
<template>
    <ui-main class="scoped-coupon-details">
        <div v-loading="isLoading" class="p15 flex flex-1">
            <!-- 彩金详情区 -->
            <div class="flex-6">

                <!-- 优惠券 -->
                <el-card class="card auto-center">
                    <div class="flex">
                        <div class="flex-1">
                            <div class="mb15 flex col-center">
                                <ui-img :url="d.company_ico" size="50px" class="ui-circle bg-grey mr5"></ui-img>
                                <span class="clamp-1 flex-1 f20">{{d.name}}</span>
                            </div>
                            <div class="mb15 f-color-text">
                                <span class="mr10">
                                    <span v-if="d.is_identify==1">
                                        <img src="~@/icons/verify01.png" style="width:15px">
                                        公司认证
                                    </span>
                                    <span v-else>
                                        <img src="~@/icons/verify01_grey.png" style="width:15px">
                                        未认证
                                    </span>
                                </span>
                                <span>
                                    <span v-if="d.is_cert==1">
                                        <img src="~@/icons/verify02.png" style="width:15px">
                                        已验
                                    </span>
                                    <span v-else>
                                        <img src="~@/icons/verify02_grey.png" style="width:15px">
                                        未验
                                    </span>
                                </span>
                            </div>
                            <div class="f10">
                                <span class="f-color-grey mr15">{{d.update_time}}</span>
                                <span class="f-color-orange">{{d.company_name}}</span>
                            </div>
                        </div>
                        <div class="flex column column-col-around column-row-center pl20 ui-border-left">
                            <el-button @click="receive" :disabled="isReceive || !!invaildMsg" :loading="receiveCooling" type="primary" class="f20">
                                <span v-if="isReceive">已领</span>
                                <span v-if="!isReceive">领取</span>
                            </el-button>
                            <span class="f-color-grey f14">
                                <i v-if="invaildMsg">{{invaildMsg}}</i>
                                <i v-else>有效期: {{getDayLeft}}天</i>
                            </span>
                        </div>
                    </div>
                </el-card>

                <!-- 详细信息 -->
                <div class="f10 pt20 pb20 flex column">
                    <!--相关数据-->
                    <div class="items">
                        <div class="item">
                            <img src="~@/icons/person.png">
                            <span>
                                <span class="f-color-orange">{{d.draw_num}}</span>人
                            </span>
                            <span class="item-name">已领取</span>
                        </div>
                        <div class="item">
                            <img src="~@/icons/get2.png">
                            <span>
                                <span class="f-color-orange">{{d.withdraw_num}}</span>人
                            </span>
                            <span class="item-name">已提款</span>
                        </div>
                        <div class="item" v-for="item in d.gameTypes">
                            <img :src="item.pic" style="height:20px">
                            <span class="item-name">{{item.name}}</span>
                        </div>
                        <div class="item">
                            <img src="~@/icons/cup2.png" >
                            <span class="opacity-08">{{d.multiple}}杯</span>
                            <span class="item-name">流水要求</span>
                        </div>
                        <div class="item">
                            <img src="~@/icons/tk2.png" >
                            <span class="opacity-08">{{ d.r_limit==0 ? '不限制' : parseInt(d.r_limit)+'元' }}</span>
                            <span class="item-name">最高提款</span>
                        </div>
                        <div class="item">
                            <img src="~@/icons/leaf2.png" >
                            <span class="opacity-08">0.00</span>
                            <span class="item-name">有机值</span>
                        </div>
                    </div>

                    <ui-title class="mt30">领取要求</ui-title>
                    <div v-if="d.couponRequest && d.couponRequest.length>0" class="pl1 mb1">
                        <div class="items">
                            <div class="item" v-for="item in d.couponRequest">
                                <img :src="item.logo_pic" style="height:1.5rem">
                                <span class="item-name">{{item.short_name}}</span>
                            </div>
                        </div>
                    </div>

                    <!--已领优惠码-->
                    <div v-if="userDraw" class="mt30 mb50">
                        <div v-if="drawCodeArry.length>0">
                            <ui-title>优惠码</ui-title>
                            <p v-for="code in drawCodeArry" class="f-color-orange"> {{code}} </p>
                        </div>
                        <div v-if="drawUrlArry.length>0">
                            <ui-title>领取地址</ui-title>
                            <a :href="d.url" target="_blank" class="f-color-blue block">{{d.url}}</a>
                        </div>
                    </div>

                    <!--活动规则-->
                    <div v-if="d.desc" class="flex column">
                        <ui-title>瞪大眼睛</ui-title>
                        <div class="f16 f-color-text mb10" v-html="d.eye_content"></div>
                        <ui-title>必读：官方活动规则</ui-title>
                        <div class="f16 f-color-text" v-html="d.desc">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 评论区 -->
            <div class="flex-4 pl30">
                <ui-title>评论晒图</ui-title>
                <div class="upload-list mb10">
                    <!-- 上传列表 -->
                    <el-upload
                    :action="$http.config.baseURL + '/index.php?g=asset&m=asset&a=plupload'"
                    list-type="picture-card"
                    :on-preview="uploadPictureCardPreview"
                    :on-remove="uploadRemove"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess" 
                    :with-credentials="true"
                    :data="{app:'companyApply'}"
                    :file-list="uploadFileList"
                    :multiple="true"
                    >
                    <i class="el-icon-plus"></i>
                    </el-upload>
                </div>
                <el-input v-model="commentText" type="textarea"></el-input>
                <div class="flex row-between mb20">
                    <span class="f-color-grey f10 mt10">共 {{commentText.length}} 字符，最多200字。</span>
                    <el-button @click="doComment({postId:id})" :loading="commentLoading" type="primary" class="ui-button-large mt10">发布</el-button>
                </div>

                <ui-title>评论记录</ui-title>
                <div v-for="commentItem in commentData" class="mb30">
                    <div class="flex row-between">
                        <div class="flex col-center">
                            <ui-img :url="commentItem.avatar" size="40px" class="ui-circle bg-grey mr10"></ui-img>
                            <div>
                                <div class="f-color-orange mr20">{{commentItem.user_nicename || '匿名'}}
                                    <el-tag v-if="commentItem.is_top" type="success" class="ml10">客服代表</el-tag>
                                    <!-- <i class="f-color-grey f10 ml5">#{{commentItem.id}}</i> -->
                                </div>
                                <div class="f10 f-color-grey">{{commentItem.createtime_show}}</div>
                            </div>
                        </div>
                        <div class="flex">
                            <el-button @click="replyComment(commentItem)" type="text" class="reply">回复</el-button> 
                            <div @click="doLike(commentItem, 'comments')" class="flex col-center cursor-pointer f-color-text">
                                <icon v-if="commentItem.liked" name="heart" class="mr5 f-color-red"></icon>
                                <icon v-else name="heart-o" class="mr5"></icon>
                                {{commentItem.like_num}}赞
                            </div>
                        </div>
                    </div>
                    <div class="p15" v-html="commentItem.content"></div>
                    <div class="flex flex-wrap">
                        <ui-img v-for="(img,i) in commentItem.smeta" v-if="img" :key="img + i" :url="img" @click.native="imgPreview(img)" class="bg-grey mb10 mr10 cursor-pointer ui-hover-shadow" style="width:140px;height:100px"></ui-img>
                    </div>
                    <!-- 评论回复 -->
                    <div class="ml30 ui-border-bottom">
                        <div v-for="replyItem in commentItem.son" class="mt20 mb20">
                            <div class="flex col-center">
                                <ui-img :url="replyItem.avatar" size="40px" class="ui-circle bg-grey mr10"></ui-img>
                                <div>
                                    <div class="f-color-orange mr20">{{replyItem.user_nicename || '匿名'}}</div>
                                    <div class="f-color-grey f10">{{replyItem.createtime_show}}</div>
                                </div>
                                <div class="flex-1 ml10" v-html="replyItem.content"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 看大图 -->
        <el-dialog :visible.sync="commentImgPreview" top="0" class="ui-img-preview">
            <img :src="commentImgPreviewSrc" @click="commentImgPreview=false" class="auto-center block" style="max-width:1200px;max-height:600;">
        </el-dialog>

        <!-- 上传 -->
        <el-dialog v-model="uploadDialogVisible" size="tiny">
            <img width="100%" :src="uploadImgSrc">
        </el-dialog>
    </ui-main>
</template>
<script>
    export default {
        data() {
            return {
                isLoading:false,
                d:{},//优惠劵数据
                id:this.$route.query.id ,//当前优惠券id

                // 评论
                commentData: [],//评论数据
                commentText:'',
                commentInputFocus:false,//评论输入框高度
                commentImgPreview:false,//阅览大图
                commentImgPreviewSrc:'',
                commentLoading:false,

                activityRules: false, //活动规则是否开启

                userDraw:null,//当前用户优惠券领取状态

                receiveCooling:false,

                isReceive:false,

                invaildMsg:'',//无法领取的原因

                uploadImgSrc:'',
                uploadDialogVisible:false,
                uploadImgs:'',//已上传图片列url, 多张以逗号分隔
                uploadFileList:[],//已上传的图片列表

            }
        },
        created () {
            this.isLoading = true
            // 获取优惠券数据
            this.$http.get('index.php?g=home&m=GameCoupon&a=coupon_detail',{
                    params:{
                        id: this.id
                    }
                }).then(({data}) => {
                    console.log('优惠券详情:', data);
                    this.isLoading = false
                    if (data.code===1) {
                        this.d = data.data
                    }else if(data.msg){
                        this.$alert(data.msg, {
                            confirmButtonText: '确定',
                            callback: () => {
                                this.$router.go(-1)
                            }
                        });
                    }
                }).catch(() => {
                    this.$message({
                        message:'服务器错误,请稍后再试!',
                        type:'error',
                        showClose:true
                    })
                    this.isLoading = false
                })

            // 检测优惠券领取状态
            this.checkUserDraw()

            // 获取评论
            this.getCommentData()
        },
        computed: {
            getDayLeft(){ //计算剩余时间
                function transformTime(str) {
                    // 移动端时间格式跟pc不同, 用这个函数统一转换
                    str = str.replace(/-/g, '/');
                    var time = (new Date(str)).getTime();
                    return time;
                }
                if (this.d.end_time) {
                    let end = transformTime(this.d.end_time)
                    let today = Date.parse(new Date())
                    let lastDay = new Date(end - today).getDate()

                    return lastDay || 0
                }else{
                    return 0
                }
            }, 
            drawCodeArry(){
                let arr = this.userDraw.exchanges
                let resArr = []
                if (this.userDraw && arr) {
                    arr.forEach((item)=>{
                        if (item.code) {
                            resArr.push(item.code)
                        }
                    })
                }
                return resArr
            },
            drawUrlArry(){
                let arr = this.userDraw.exchanges
                let resArr = []
                if (this.userDraw && arr) {
                    arr.forEach((item)=>{
                        if (item.url) {
                            resArr.push(item.url)
                        }
                    })
                }
                return resArr
            },
        },
        methods: {
            getCommentData(){// 获取评论数据
                this.$http.get('index.php?g=home&m=Comments&a=comments_list',{
                    params:{
                        post_id: this.$route.query.id,
                        post_table: 'game_coupon'
                    }
                }).then(({data}) => {
                    console.log('优惠券详情-评论:', data);
                    if (data.code===1) {
                        this.commentData = data.data
                    }
                })
            },
            receive(){ //领取优惠券
                this.receiveCooling = true
                this.$http.post('index.php?g=home&m=GameCoupon&a=draw',{
                    id: this.id
                }).then(({data}) => {
                    this.receiveCooling = false
                    // console.log('领取优惠券结果:', data);
                    if (data.code==1) {
                        this.isReceive = true//标记本次已领取
                        this.$message.success('领取成功')
                        this.checkUserDraw()//刷新领取的优惠券数据
                    }else{
                        this.$message.error(data.msg)
                    }
                }).catch(e=>{
                    this.$message.error('领取失败')
                    this.receiveCooling = false
                    console.warn('领取接口请求失败', e);
                })
            },
            checkUserDraw(){// 检测领取状态
                this.$http.get('index.php?g=home&m=GameCoupon&a=check_user_draw', {
                    params:{
                        coupon_id:this.id
                    }
                })
                .then(({data})=>{
                    // console.log('优惠券领取状态:',data)
                    if (data.code===1) {
                        this.userDraw = data.data
                        this.invaildMsg = data.data.reason
                    }
                })
            },
            imgPreview(src){//阅览大图
                this.commentImgPreviewSrc = src
                this.commentImgPreview = true
            },
            doLike(item, type){//点赞
                this.$http.post('index.php?g=home&m=Like&a=do_like',{
                    id: item.id,
                    table: type,
                    type: 1,
                })
                .then(({data}) => {
                    this.$message.success(data.msg)
                    console.log('点赞结果:', data);
                    if (data.code==1) {
                        // 点赞成功
                        item.like_num ++ //点赞数+1
                        this.$set(item, 'liked', true) //增加一个已点赞字段,用来改变桃心样式
                    }
                })
            },
            doComment({content=this.commentText,type='game_coupon',postId='',toUid='',level}){//发评论
                if (type==='game_coupon') {
                    this.commentLoading=true
                }
                this.$http.post('index.php?g=home&m=Comments&a=post_comments',{
                    content: content,
                    post_table: type,
                    post_id: postId,
                    to_uid:toUid,
                    level:level,
                    img:this.uploadImgs,
                    url: '/#' + this.$route.fullPath, //原文地址 (后台需要的)
                })
                .then(({data})=>{
                    console.log('发评论:', data)
                    if (type==='game_coupon') {
                        this.commentLoading = false
                    }
                    this.$message(data.msg)
                    if (data.code===1) {
                        // 发送完毕,清空输入框
                        if (type==='game_coupon') {
                            this.commentText = ''
                            this.uploadImgs=''//清空已上传的图片url列表
                            this.uploadFileList=[]//清空上传控件图片列表
                        }
                        // 重新获取评论数据
                        this.getCommentData()
                    }
                })
            },
            replyComment(item) {//回复评论
                this.$prompt('回复评论', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValidator:function(val){
                        return !!val
                    },
                    inputErrorMessage:'回复内容不能为空'
                }).then(({ value }) => {
                    this.doComment({
                        content:value,
                        type:'comments',
                        postId:item.id,
                        toUid:item.uid,
                        level:item.level
                    })
                }).catch(() => {
                });
            },
            uploadRemove(file, fileList) {
                // console.log(file, fileList);
                let removeFileUrl = file.response.data.filepath
                this.uploadImgs = this.uploadImgs.replace(removeFileUrl+',', '')
            },
            uploadPictureCardPreview(file) {
              this.uploadImgSrc = file.url;
              this.uploadDialogVisible = true;
            },
            // 图片上传
            beforeUpload(file) {

                const typeVaild = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!typeVaild) {
                    this.$message.error('图片只能是 JPG 或 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('图片大小不能超过 2MB!');
                }

                let vaild = typeVaild && isLt2M

                if (vaild) {
                    this.uploading = true//开启上传冷却
                }

                return vaild
            },
            uploadSuccess(res, file){
                console.log('图片上传完成:', res);
                console.log('file', file);
                if (res.code===1) {
                    this.uploadImgs += res.data.filepath + ','

                    // 生成本地预览
                    this.uploadImgSrc = URL.createObjectURL(file.raw)
                }
            },
        },
        watch: {
            commentText(v){
                let max = 200
                if (v.length>=max) {
                    this.$message.warn(`评论最多${max}字符`)
                }
            },
        }
    }
</script>